#include "CServer.h"
#include "CSession.h"
#include "AsioIOServicePool.h"	

#include <iostream>

CServer::CServer(boost::asio::io_context& ioc, unsigned short port) 
	: m_port(port)
	, m_ioc(ioc)
	, m_acceptor( ioc, boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), port) )
{
	std::cout << "Server start success, listen on port : " << m_port << std::endl;
	startAccept();
}

CServer::~CServer() {
	std::cout << "Server destruct listen on port : " << m_port << std::endl;
}

void CServer::clearSession(std::string uuid)
{
	std::lock_guard<std::mutex> lock(m_mtx);
	m_sesssions_map.erase(uuid);
} 

// 接受连接
void CServer::startAccept()
{
	auto& ioc = AsioIOServicePool::getInstance()->getIOService();
	std::shared_ptr<CSession> new_session = std::make_shared<CSession>(ioc, this);
	m_acceptor.async_accept(new_session->getSocket(), std::bind(&CServer::handleAccept, this, new_session, std::placeholders::_1));
}

// 处理连接的回调
void CServer::handleAccept(std::shared_ptr<CSession> new_session, const boost::system::error_code& err)
{
	if (!err) {
		// 启动连接
		new_session->start();
		std::lock_guard<std::mutex> lock(m_mtx);
		m_sesssions_map.insert( {new_session->getUuid(), new_session} );
	}
	else {
		std::cout << "session accept failed, error is " << err.what() << std::endl;
	}

	// 继续监听对端的连接
	startAccept();
}

